//
//  TCPlayDecorateView.m
//
//  Created by zhangxiang on 16/8/1.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "TCPlayDecorateView.h"
#import "TCMsgBulletView.h"
#import "TCPlayerModel.h"
#import "UIImage+Additions.h"
#import "TCUserInfoModel.h"
#import "TCLoginModel.h"
#import "TCConstants.h"
#import "TCLiveListModel.h"
#import "HUDHelper.h"
//#import "UMSocialUIManager.h"
//#import <UMSocialCore/UMSocialCore.h>

#import "MessageTableViewCell.h"
#import "ConversationListViewController.h"

#import "UIView+LZCView.h"

// 模态半屏
#import "UIViewController+KNSemiModal.h"
#import "MessageViewController.h"
#import "privateChat.h"

@implementation TCPlayDecorateView
{
    TCShowLiveTopView  *_topView;
    TCAudienceListTableView *_audienceTableView;
    TCMsgListTableView *_msgTableView;
    TCMsgBulletView *_bulletViewOne;
    TCMsgBulletView *_bulletViewTwo;
    TCLiveInfo         *_liveInfo;
    UIButton           *_praiseBtn;
    UIButton           *_closeBtn;
    UIView             *_msgInputView;
    UITextField        *_msgInputFeild;
    CGPoint            _touchBeginLocation;
    BOOL               _bulletBtnIsOn;
    BOOL               _viewsHidden;
    NSMutableArray     *_heartAnimationPoints;
    
    
    UILabel             *_xiubi;
    
    NSTimer             *_timer;   // 定时器 （创建房间开始几时，如果10分钟没有用户进入房间，就请求网络，若有就停止）
    int                 _second;    // 禁言时间
    
    liwuview             *giftview;//礼物界面
    
    NSString            *_receiveInfo; // 私聊对象信息
    UITableView         *_tableView; // 私聊列表
    UITableView         *_tableView2;// 私聊对话列表
    UIView              *_textBgView;// 私聊底部对话框
    UITextField         *_privateChatTextF; // 私聊输入框
    
    UIView              *_msgView;
    
    TIMConversation     *_currConversation; // 当前会话
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    //判断如果点击的是tableView的cell，就把手势给关闭了
    if ([touch.view isDescendantOfView:giftview]) {
        return NO;//关闭手势
    }//否则手势存在
    return YES;
}

-(instancetype)initWithFrame:(CGRect)frame liveInfo:(TCLiveInfo *)liveInfo withLinkMic:(BOOL)linkmic{
    self = [super initWithFrame:frame];
    if (self) {
        _liveInfo      = liveInfo;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLogout:) name:logoutNotification object:nil];
        
        //腾讯的tap手势，先注释
		/*
        //UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickScreen:)];
        UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doDoubleTapped:)];
        
        tap.delegate = self;
        [self addGestureRecognizer:tap];
		 */
        [self initUI: linkmic];
        
        _second = 0;
        
        // 注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendGiftMsg:)name:@"sendGiftMsg" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendBannedMsg:)name:@"sendBannedMsg1" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendRemoveAudienceMsg:)name:@"sendRemoveAudienceMsg1" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendPrivateChatMsg:)name:@"sendPrivateChatMsg1" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(c2cNotification:)name:@"c2cNotification" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SendFavoritesMsg:)name:@"SendFavoritesMsg" object:nil];
        
        
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sendGiftMsg" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sendBannedMsg1" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sendRemoveAudienceMsg1" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sendPrivateChatMsg1" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"c2cNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"SendFavoritesMsg" object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)setViewerCount:(int)viewerCount likeCount:(int)likeCount
{
    _liveInfo.viewercount = viewerCount;
    _liveInfo.likecount = likeCount;
    
    [_topView setViewerCount:viewerCount likeCount:likeCount];
}

-(BOOL)isAlreadyInAudienceList:(TCMsgModel *)model
{
    return [_audienceTableView isAlreadyInAudienceList:model];
}

- (void)setMsgHandler:(AVIMMsgHandler *)msgHandler {
    _msgHandler = msgHandler;
    _msgHandler.roomIMListener = self;
//    [[TCLoginModel sharedInstance] setGroupAssistantListener:self];
}

- (void)initAudienceList {
    CGFloat audience_width = self.width - 25 - _topView.right;
    _audienceTableView = [[TCAudienceListTableView alloc] initWithFrame:CGRectMake(_topView.right + 10 +audience_width / 2 - IMAGE_SIZE / 2 ,_topView.center.y -  audience_width / 2, _topView.height, audience_width) style:UITableViewStyleGrouped liveInfo:_liveInfo];
    _audienceTableView.transform = CGAffineTransformMakeRotation(- M_PI/2);
    _audienceTableView.audienceListDelegate = self;
    
    [self addSubview:_audienceTableView];
}

- (void)initUI:(BOOL)linkmic {
    //close VC
    _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeBtn setFrame:CGRectMake(self.width - 15 - BOTTOM_BTN_ICON_WIDTH, self.height - 50, BOTTOM_BTN_ICON_WIDTH, BOTTOM_BTN_ICON_WIDTH)];
    [_closeBtn setImage:[UIImage imageNamed:@"live_close"] forState:UIControlStateNormal];
    [_closeBtn addTarget:self action:@selector(closeVC) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_closeBtn];
    _closeBtn.tag = 10000;
    
    //topview,展示主播头像，在线人数及点赞
    int statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
    _topView = [[TCShowLiveTopView alloc] initWithFrame:CGRectMake(5, statusBarHeight + 5, 150, 35) isHost:NO hostNickName:_liveInfo.userinfo.nickname
                                          audienceCount:_liveInfo.viewercount likeCount:_liveInfo.likecount hostFaceUrl:_liveInfo.userinfo.headpic isVIP:@"2" isLike:_liveInfo.isLike hostId:_liveInfo.myuserid roomId:_liveInfo.groupid];
    
    [self addSubview:_topView];
    
    //秀币
    UILabel *showCoin = [[UILabel alloc] init];
//                         WithFrame:CGRectMake(_topView.left, _topView.bottom + 10, 60, 20)];
    showCoin.textColor = [UIColor whiteColor];
    [showCoin setFrame:CGRectMake(_topView.left, _topView.bottom + 10, 50, 20)];
    [self addSubview:showCoin];
    showCoin.backgroundColor = RGBA(50, 50, 50, 0.5);
    showCoin.font = kUHSystemFontWithSize(10);
    showCoin.text = [NSString stringWithFormat:@"秀币 %@个", _liveInfo.money];
//    NSMutableAttributedString *hintString = [[NSMutableAttributedString alloc] initWithString:showCoin.text];
    //获取要调整颜色的文字位置,调整颜色
//    NSRange range1=[[hintString string]rangeOfString:@"秀币"];
//    [hintString addAttribute:NSForegroundColorAttributeName value:RGB(225, 181, 52) range:range1];
//    
//    showCoin.attributedText = hintString;
    CGSize coinSize = [LZCTools textSizeWithText:showCoin.text font:kUHSystemFontWithSize(10)];
    showCoin.frame = CGRectMake(_topView.left, _topView.bottom, coinSize.width+SW(6), coinSize.height+5);
    showCoin.layer.cornerRadius = (coinSize.height+5)/2;
    showCoin.layer.masksToBounds = YES;
    showCoin.textAlignment = NSTextAlignmentCenter;
    
    _xiubi = showCoin;
    
    // 水印
    UIButton *watermark = [UIButton buttonWithType:UIButtonTypeCustom];
    //[self addSubview:watermark];
    [watermark setImage:IMAGE(@"watermark") forState:UIControlStateNormal];
    watermark.userInteractionEnabled = NO;
    watermark.frame = CGRectMake(self.width-_topView.left-SW(4), _topView.bottom+10, SW(4), SW(8));
    
    // 贡献榜
    UILabel *contribution = [[UILabel alloc] init];
    contribution.textColor = [UIColor whiteColor];
    [self addSubview:contribution];
    contribution.backgroundColor = RGBA(50, 50, 50, 0.5);
    contribution.font = kUHSystemFontWithSize(10);
    contribution.text = @"  贡献榜 2345 >";
    // 创建一个富文本
    NSMutableAttributedString *hintString2 = [[NSMutableAttributedString alloc] initWithString:contribution.text];
    //获取要调整颜色的文字位置,调整颜色
    NSRange range2=[[hintString2 string]rangeOfString:@"贡献榜"];
    [hintString2 addAttribute:NSForegroundColorAttributeName value:RGB(225, 181, 52) range:range2];
    // 添加表情
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 表情图片
    attch.image = [UIImage imageNamed:@"live_gxb"];
    // 设置图片大小
    attch.bounds = CGRectMake(2.5, -2.5, coinSize.height, coinSize.height);
    // 创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    NSMutableAttributedString *string2 = [[NSMutableAttributedString alloc] initWithAttributedString:string];
    [string2 appendAttributedString:hintString2];
    
    // 用label的attributedText属性来使用富文本
    contribution.attributedText = string2;
    CGSize contributionSize = [LZCTools textSizeWithText:contribution.text font:kUHSystemFontWithSize(10)];

    contribution.frame = CGRectMake(self.width-_topView.left-(contributionSize.width+15), _topView.bottom+10, contributionSize.width+15, contributionSize.height+5);
    contribution.layer.cornerRadius = contribution.height/2;
    contribution.layer.masksToBounds = YES;
    contribution.textAlignment = NSTextAlignmentCenter;
    [contribution addTarget:self action:@selector(contributionClick:)];
    
    contribution.hidden = YES;
    
    // -------------
    
    int   icon_size = BOTTOM_BTN_ICON_WIDTH;
    float startSpace = 15;
    float icon_center_y = self.height - icon_size/2 - startSpace;
    
    if (_liveInfo.type == TCLiveListItemType_Record || _liveInfo.type == TCLiveListItemType_UGC) {  //点播
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBtn setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        [_playBtn setFrame:CGRectMake(15, _closeBtn.y, BOTTOM_BTN_ICON_WIDTH, BOTTOM_BTN_ICON_WIDTH)];
        [_playBtn addTarget:self action:@selector(clickPlayVod) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_playBtn];

        _playLabel = [[UILabel alloc]init];
        _playLabel.frame = CGRectMake(_playBtn.right + 10, _playBtn.center.y - 5, 53, 10);
        [_playLabel setText:@"00:00:00"];
        [_playLabel setTextAlignment:NSTextAlignmentRight];
        [_playLabel setFont:[UIFont systemFontOfSize:12]];
        [_playLabel setTextColor:[UIColor whiteColor]];
        [self addSubview:_playLabel];
        
        UILabel *centerLabel =[[UILabel alloc]init];
        centerLabel.frame = CGRectMake(_playLabel.right, _playLabel.y, 4, 10);
        centerLabel.text = @"/";
        centerLabel.font = [UIFont systemFontOfSize:12];
        centerLabel.textColor = [UIColor whiteColor];
        centerLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:centerLabel];

        _playDuration = [[UILabel alloc]init];
        _playDuration.frame = CGRectMake(centerLabel.right, centerLabel.y, 53, 10);
        [_playDuration setText:@"--:--:--"];
        [_playDuration setFont:[UIFont systemFontOfSize:12]];
        [_playDuration setTextColor:[UIColor whiteColor]];
        [self addSubview:_playDuration];
        
        //log显示或隐藏
        _btnLog = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnLog.center = CGPointMake(_closeBtn.center.x - icon_size - 15, icon_center_y);
        _btnLog.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_btnLog setImage:[UIImage imageNamed:@"log"] forState:UIControlStateNormal];
        [_btnLog addTarget:self action:@selector(clickLog:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_btnLog];
        _btnLog.hidden = YES;
        
        _btnShare = ({
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//            [self addSubview:btn];
            btn.center = CGPointMake(_closeBtn.center.x - (icon_size + 15) * 2, icon_center_y);
            btn.bounds = CGRectMake(0, 0, icon_size, icon_size);
            [btn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"share_pressed"] forState:UIControlStateHighlighted];
            [btn addTarget:self action:@selector(clickShare:) forControlEvents:UIControlEventTouchUpInside];
            btn;
        });
        
        _playProgress=[[UISlider alloc]initWithFrame:CGRectMake(15, _playBtn.top - 35, self.width - 30, 20)];
        [_playProgress setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
        [_playProgress setMinimumTrackImage:[UIImage imageNamed:@"green"] forState:UIControlStateNormal];
        [_playProgress setMaximumTrackImage:[UIImage imageNamed:@"gray"] forState:UIControlStateNormal];
        _playProgress.maximumValue = 0;
        _playProgress.minimumValue = 0;
        _playProgress.value = 0;
        _playProgress.continuous = NO;
        [_playProgress addTarget:self action:@selector(onSeek:) forControlEvents:(UIControlEventValueChanged)];
        [_playProgress addTarget:self action:@selector(onSeekBegin:) forControlEvents:(UIControlEventTouchDown)];
        [_playProgress addTarget:self action:@selector(onDrag:) forControlEvents:UIControlEventTouchDragInside];
        [self addSubview:_playProgress];
    }else{    //直播
        //聊天
        float icon_count = (linkmic == YES ? 8 : 6);
        float icon_center_interval = (self.width - 2*startSpace - icon_size)/(icon_count - 1);
        float first_icon_center_x = startSpace + icon_size/2;
        
        _btnChat = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnChat.center = CGPointMake(first_icon_center_x, icon_center_y);
        _btnChat.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_btnChat setImage:[UIImage imageNamed:@"live_chat"] forState:UIControlStateNormal];
        [_btnChat addTarget:self action:@selector(clickChat:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_btnChat];
        _btnChat.tag = 10000;
        
        //点赞
        _praiseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _praiseBtn.center = CGPointMake(_closeBtn.center.x - icon_center_interval, icon_center_y-icon_size-10);
        _praiseBtn.bounds = CGRectMake(0, 0, icon_size, icon_size);
//        [_praiseBtn setImage:[UIImage imageNamed:@"like_hover"] forState:UIControlStateNormal];
        [_praiseBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
//        [_praiseBtn addTarget:self action:@selector(clickPraise:) forControlEvents:UIControlEventTouchUpInside];
//        [self addSubview:_praiseBtn];
        
        //log显示或隐藏
        _btnLog = [UIButton buttonWithType:UIButtonTypeCustom];
        //_btnLog.center = CGPointMake(_closeBtn.center.x - icon_size * 2 - 15 * 2, icon_center_y);
//        _btnLog.center = CGPointMake(_closeBtn.center.x - icon_center_interval * 2, icon_center_y);
        _btnLog.center = CGPointMake(_closeBtn.center.x - icon_center_interval * 2, icon_center_y-icon_size-10);
        _btnLog.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_btnLog setImage:[UIImage imageNamed:@"log"] forState:UIControlStateNormal];
        [_btnLog addTarget:self action:@selector(clickLog:) forControlEvents:UIControlEventTouchUpInside];
//        [self addSubview:_btnLog];
        _btnLog.hidden = YES;
        
        //礼物显示或隐藏
        _btnGift = [UIButton buttonWithType:UIButtonTypeCustom];
//        _btnGift.center = CGPointMake(_closeBtn.center.x - icon_center_interval * 2, icon_center_y);
        _btnGift.center = CGPointMake(_closeBtn.center.x - icon_center_interval, icon_center_y);
        _btnGift.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_btnGift setImage:[UIImage imageNamed:@"live_gift"] forState:UIControlStateNormal];
        [_btnGift addTarget:self action:@selector(clickGift:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_btnGift];
        _btnGift.tag = 10000;
		if (![LZCTools thinkEnv]) {
			_btnGift.hidden = YES;
		}
        
        
        _btnShare = ({
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//            [self addSubview:btn];
            //btn.center = CGPointMake(_closeBtn.center.x - (icon_size + 15) * 3, icon_center_y);
            btn.center = CGPointMake(_closeBtn.center.x - icon_center_interval, icon_center_y);
            btn.bounds = CGRectMake(0, 0, icon_size, icon_size);
            [btn setImage:[UIImage imageNamed:@"live_share"] forState:UIControlStateNormal];
//            [btn setImage:[UIImage imageNamed:@"share_pressed"] forState:UIControlStateHighlighted];
            [btn addTarget:self action:@selector(clickShare:) forControlEvents:UIControlEventTouchUpInside];
            btn;
        });
        _btnShare.hidden = YES;
        
        //UGC
        _btnRecord = [UIButton buttonWithType:UIButtonTypeCustom];
//        _btnRecord.center = CGPointMake(_closeBtn.center.x - icon_center_interval * 4, icon_center_y);
        _btnRecord.center = CGPointMake(_closeBtn.center.x - icon_center_interval * 4, icon_center_y-icon_size-10);
        _btnRecord.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_btnRecord setImage:[UIImage imageNamed:@"video_record"] forState:UIControlStateNormal];
        [_btnRecord setImage:[UIImage imageNamed:@"video_record_press"] forState:UIControlStateHighlighted];
        [_btnRecord addTarget:self action:@selector(clickRecord:) forControlEvents:UIControlEventTouchUpInside];
//        [self addSubview:_btnRecord];
        
        //弹幕
        _msgTableView = [[TCMsgListTableView alloc] initWithFrame:CGRectMake(15, _btnChat.top - MSG_TABLEVIEW_HEIGHT - MSG_TABLEVIEW_BOTTOM_SPACE, MSG_TABLEVIEW_WIDTH+30, MSG_TABLEVIEW_HEIGHT) style:UITableViewStyleGrouped];
        [self addSubview:_msgTableView];
        
        _bulletViewOne = [[TCMsgBulletView alloc]initWithFrame:CGRectMake(0,_msgTableView.top - MSG_UI_SPACE - MSG_BULLETVIEW_HEIGHT, SCREEN_WIDTH, MSG_BULLETVIEW_HEIGHT)];
        [self addSubview:_bulletViewOne];
        
        _bulletViewTwo = [[TCMsgBulletView alloc]initWithFrame:CGRectMake(0, _bulletViewOne.top - MSG_BULLETVIEW_HEIGHT, SCREEN_WIDTH, MSG_BULLETVIEW_HEIGHT)];
        [self addSubview:_bulletViewTwo];
        
        
        //输入框
        _msgInputView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height, self.width, MSG_TEXT_SEND_VIEW_HEIGHT )];
        _msgInputView.backgroundColor = [UIColor clearColor];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _msgInputView.width, _msgInputView.height)];
        imageView.image = [UIImage imageNamed:@"input_comment"];
        
        UIButton *bulletBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        bulletBtn.frame = CGRectMake(10, (_msgInputView.height - MSG_TEXT_SEND_FEILD_HEIGHT)/2, MSG_TEXT_SEND_BULLET_BTN_WIDTH, MSG_TEXT_SEND_FEILD_HEIGHT);
        [bulletBtn setImage:[UIImage imageNamed:@"Switch_OFF"] forState:UIControlStateNormal];
        [bulletBtn setImage:[UIImage imageNamed:@"Switch_ON"] forState:UIControlStateSelected];
        [bulletBtn addTarget:self action:@selector(clickBullet:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sendBtn.frame = CGRectMake(self.width - 15 - MSG_TEXT_SEND_BTN_WIDTH, (_msgInputView.height - MSG_TEXT_SEND_FEILD_HEIGHT)/2, MSG_TEXT_SEND_BTN_WIDTH, MSG_TEXT_SEND_FEILD_HEIGHT);
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [sendBtn setTitleColor:UIColorFromRGB(0x0ACCAC) forState:UIControlStateNormal];
        [sendBtn setBackgroundColor:[UIColor clearColor]];
        [sendBtn addTarget:self action:@selector(clickSend) forControlEvents:UIControlEventTouchUpInside];
        
        UIImageView *msgInputFeildLine1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"vertical_line"]];
        msgInputFeildLine1.frame = CGRectMake(bulletBtn.right + 10, sendBtn.y, 1, MSG_TEXT_SEND_FEILD_HEIGHT);
        
        UIImageView *msgInputFeildLine2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"vertical_line"]];
        msgInputFeildLine2.frame = CGRectMake(sendBtn.left - 10, sendBtn.y, 1, MSG_TEXT_SEND_FEILD_HEIGHT);
        
        _msgInputFeild = [[UITextField alloc] initWithFrame:CGRectMake(msgInputFeildLine1.right + 10,sendBtn.y,msgInputFeildLine2.left - msgInputFeildLine1.right - 20,MSG_TEXT_SEND_FEILD_HEIGHT)];
        _msgInputFeild.backgroundColor = [UIColor clearColor];
        _msgInputFeild.returnKeyType = UIReturnKeySend;
        _msgInputFeild.placeholder = @"和大家说点什么吧";
        _msgInputFeild.delegate = self;
        _msgInputFeild.textColor = [UIColor blackColor];
        _msgInputFeild.font = [UIFont systemFontOfSize:14];
        
        
        [_msgInputView addSubview:imageView];
        [_msgInputView addSubview:_msgInputFeild];
        [_msgInputView addSubview:bulletBtn];
        [_msgInputView addSubview:sendBtn];
        [_msgInputView addSubview:msgInputFeildLine1];
        [_msgInputView addSubview:msgInputFeildLine2];
        [self addSubview:_msgInputView];
        
        // 私聊
        _btnPrivateChat = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnPrivateChat.center = CGPointMake(_closeBtn.center.x - icon_center_interval * 2, icon_center_y);
        _btnPrivateChat.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_btnPrivateChat setImage:[UIImage imageNamed:@"live_per_info"] forState:UIControlStateNormal];
        [_btnPrivateChat addTarget:self action:@selector(clickPrivateChat:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_btnPrivateChat];
        _btnPrivateChat.tag = 10000;
        
        // 标清高清
        _btnAlert = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnAlert.center = CGPointMake(_closeBtn.center.x - icon_center_interval * 3, icon_center_y);
        _btnAlert.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_btnAlert setImage:[UIImage imageNamed:@"live_biao"] forState:UIControlStateNormal];
        [_btnAlert addTarget:self action:@selector(alertClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_btnAlert];
        
        // 下载分享
        _downShare = [UIButton buttonWithType:UIButtonTypeCustom];
        _downShare.center = CGPointMake(_closeBtn.center.x - icon_center_interval * 4, icon_center_y);
        _downShare.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_downShare setImage:[UIImage imageNamed:@"live_share"] forState:UIControlStateNormal];
        [_downShare addTarget:self action:@selector(clickDownShare:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_downShare];
        
        // 弹出框的背景View
        _qingBgView = [[UIView alloc] init];
        [self addSubview:_qingBgView];
        _qingBgView.center = CGPointMake(_closeBtn.center.x - icon_center_interval * 3, icon_center_y-(icon_size*5/3+SW(80)*2));
        _qingBgView.bounds = CGRectMake(0, 0, icon_size+SW(40), icon_size*2+SW(80)*3+10);
        //    _btnBgView.backgroundColor = [UIColor whiteColor];
        //    _btnBgView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"live_btn_bg"]];
        //    _btnBgView.alpha = 0.5;
        UIImage *image = [UIImage imageNamed:@"live_btn_bg"];
        _qingBgView.layer.contents = (id) image.CGImage;    // 如果需要背景透明加上下面这句
        _qingBgView.alpha = 0.5;
        _qingBgView.hidden = YES;
        
        
        _biaoqing = [UIButton buttonWithType:UIButtonTypeCustom];
        //    _btnTorch.center = CGPointMake( first_icon_center_x + icon_center_interval, icon_center_y);
        _biaoqing.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_biaoqing setImage:[UIImage imageNamed:@"live_biao"] forState:UIControlStateNormal];
        [_biaoqing addTarget:self action:@selector(clickBiao:) forControlEvents:UIControlEventTouchUpInside];
        //    [self addSubview:_btnTorch];
        [_qingBgView addSubview:_biaoqing];
        _biaoqing.center = CGPointMake(icon_size/2+SW(80), _qingBgView.height-icon_size-icon_size/2-SW(80)*2-SW(40));
        
        _gaoqing = [UIButton buttonWithType:UIButtonTypeCustom];
        //    _btnMusic.center = CGPointMake(first_icon_center_x + icon_center_interval*4, icon_center_y);
        
        _gaoqing.bounds = CGRectMake(0, 0, icon_size, icon_size);
        [_gaoqing setImage:[UIImage imageNamed:@"live_gao"] forState:UIControlStateNormal];
        [_gaoqing addTarget:self action:@selector(clickGao:) forControlEvents:UIControlEventTouchUpInside];
        //    [self addSubview:_btnMusic];
        [_qingBgView addSubview:_gaoqing];
        _gaoqing.center = CGPointMake(SW(80)+icon_size/2, _qingBgView.height-SW(80)-icon_size/2-SW(40));
        
        // 私聊界面
        _vChat = [[UIView  alloc] init];
        _vChat.frame = CGRectMake(0, SH(3)*2, self.width, SH(3));
        _vChat.backgroundColor = kWhiteColor;
        _vChat.hidden = YES;
        [self addSubview:_vChat];
        
        _chatHead = [[UILabel alloc] init];
        [_vChat addSubview:_chatHead];
        _chatHead.font = kUHSystemFontWithSize(14);
        _chatHead.textColor = kBlackColor;
        _chatHead.layer.borderColor = UISeparatedColorRGB.CGColor;
        _chatHead.text = [NSString stringWithFormat:@"私信"];
        _chatHead.textAlignment = NSTextAlignmentCenter;
        _chatHead.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
        
        
//        MessageViewController *msgVC = [[MessageViewController alloc] init];
        ConversationListViewController *msgVC = [[ConversationListViewController alloc] init];
        msgVC.isLive = 1;
        _nav = [[UINavigationController alloc] initWithRootViewController:msgVC];
        _msgView = _nav.view;
        [self addSubview:_msgView];
        _msgView.hidden = YES;
        
        UIButton *closeChat = [UIButton buttonWithType:UIButtonTypeCustom];
        [_vChat addSubview:closeChat];
        [closeChat setImage:[UIImage imageNamed:@"live_zhubo_close"] forState:UIControlStateNormal];
        closeChat.frame = CGRectMake(SCREEN_WIDTH-40, 0, 40, 40);
        [closeChat addTarget:self action:@selector(maskClick) forControlEvents:UIControlEventTouchUpInside];
        UIView *lineC = [[UIView alloc] initWithFrame:CGRectMake(0, _chatHead.height-1, SCREEN_WIDTH, 1)];
        [_vChat addSubview:lineC];
        lineC.backgroundColor = UISeparatedColorRGB;
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, _vChat.height-40) style:UITableViewStylePlain];
        [_vChat addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.backgroundColor = kRedColor;
        _tableView.tableFooterView = [[UIView alloc]init];
        [_tableView registerNib:[UINib nibWithNibName:@"MessageTableViewCell" bundle:nil] forCellReuseIdentifier:@"chatList"];
        
        _tableView2 = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, _vChat.height-80) style:UITableViewStylePlain];
        [_vChat addSubview:_tableView2];
        _tableView2.delegate = self;
        _tableView2.dataSource = self;
//        _tableView2.backgroundColor = kRedColor;
        _tableView2.tableFooterView = [[UIView alloc]init];
        _tableView2.hidden = YES;
//        _tableView2.backgroundColor = kYellowColor;
        
        _textBgView = [[UIView alloc] initWithFrame:CGRectMake(0, _tableView2.height+_tableView2.y, SCREEN_WIDTH, 40)];
        [_vChat addSubview:_textBgView];
        _textBgView.backgroundColor = kWhiteColor;
//        _textBgView.hidden = YES;
        
        _privateChatTextF= [[UITextField alloc] initWithFrame:CGRectMake(5, 2, SCREEN_WIDTH-10, 36)];
        [_textBgView addSubview:_privateChatTextF];
        //        _privateChatTextF.placeholder = @"我是私聊";
        _privateChatTextF.returnKeyType = UIReturnKeySend;
        _privateChatTextF.backgroundColor = UISeparatedColorRGB;
        _privateChatTextF.delegate = self;
        _privateChatTextF.layer.cornerRadius = 2;
        _privateChatTextF.layer.masksToBounds = YES;
    }
    
    //LOG UI
    _cover = [[UIView alloc]init];
    _cover.frame  = CGRectMake(10.0f, 55 + 2*icon_size, self.width - 20, self.height - 110 - 3 * icon_size);
    _cover.backgroundColor = [UIColor whiteColor];
    _cover.alpha  = 0.5;
    _cover.hidden = YES;
    [self addSubview:_cover];
    
    int logheadH = 65;
    _statusView = [[UITextView alloc] initWithFrame:CGRectMake(10.0f, 55 + 2*icon_size, self.width - 20,  logheadH)];
    _statusView.backgroundColor = [UIColor clearColor];
    _statusView.alpha = 1;
    _statusView.textColor = [UIColor blackColor];
    _statusView.editable = NO;
    _statusView.hidden = YES;
    [self addSubview:_statusView];
    
    
    _logViewEvt = [[UITextView alloc] initWithFrame:CGRectMake(10.0f, 55 + 2*icon_size + logheadH, self.width - 20, self.height - 110 - 3 * icon_size - logheadH)];
    _logViewEvt.backgroundColor = [UIColor clearColor];
    _logViewEvt.alpha = 1;
    _logViewEvt.textColor = [UIColor blackColor];
    _logViewEvt.editable = NO;
    _logViewEvt.hidden = YES;
    [self addSubview:_logViewEvt];
    
    //礼物弹窗
    giftview = [[liwuview alloc] initWithDic:nil andMyDic:nil];
    giftview.giftDelegate = self;
//    giftview.backgroundColor = kWhiteColor;
    giftview.frame = CGRectMake(0,SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT/3);
    [self addSubview:giftview];
    
}

-(void)contributionClick:(UIButton *)sender {
    NSLog(@"点击贡献榜");
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        TCUserInfoData  *userInfoData = [[TCUserInfoModel sharedInstance] getUserProfile ];
        [[TCPlayerModel sharedInstance] reportUser:_liveInfo.userid hostUserId:userInfoData.identifier handler:^(int errCode) {
            //todo
        }];
        [[HUDHelper sharedInstance] tipMessage:@"感谢你的举报，我们会尽快处理"];
    }
}

-(void)bulletMsg:(TCMsgModel *)msgModel{
    [_msgTableView bulletNewMsg:msgModel];
    if (msgModel.msgType == TCMsgModelType_DanmaMsg) {
        if ([self getLocation:_bulletViewOne] >= [self getLocation:_bulletViewTwo]) {
            [_bulletViewTwo bulletNewMsg:msgModel];
        }else{
            [_bulletViewOne bulletNewMsg:msgModel];
        }
    }
    
    if (msgModel.msgType == TCMsgModelType_MemberEnterRoom || msgModel.msgType == TCMsgModelType_MemberQuitRoom) {
        [_audienceTableView refreshAudienceList:msgModel];
    }
}



-(CGFloat)getLocation:(TCMsgBulletView *)bulletView{
    UIView *view = bulletView.lastAnimateView;
    CGRect rect = [view.layer.presentationLayer frame];
    return rect.origin.x + rect.size.width;
}


-(void)clickBullet:(UIButton *)btn{
    _bulletBtnIsOn = !_bulletBtnIsOn;
    btn.selected = _bulletBtnIsOn;
}

-(void)clickChat:(UIButton *)button{
    if (_second == 0) {
        [_msgInputFeild becomeFirstResponder];
    }
    else {
        [LZCTools HUDMessage:[NSString stringWithFormat:@"距离禁言结束还有:%ds", _second] delay:1.0f];
    }
}

-(void)clickSend{
    [self textFieldShouldReturn:_msgInputFeild];
}

-(void)clickPraise:(UIButton *)button{
    
    if ([_msgHandler sendLikeSenderInfo:_liveInfo.senderInfo]) {
        [[TCPlayerModel sharedInstance] giveLike:_liveInfo.userid handler:^(int errCode) {
        }];
        [_topView onUserSendLikeMessage];
    }
    [self showLikeHeartStartRect:button.frame];
}

-(void)clickLog:(UIButton *)button{
    if (self.delegate) [self.delegate clickLog:button];
}

- (void)clickGift:(UIButton *)button {
    NSLog(@"礼物🎁");
    
    _closeBtn.hidden = YES;
    _btnChat.hidden = YES;
    _praiseBtn.hidden = YES;
    _btnLog.hidden = YES;
    _btnGift.hidden = YES;
    _btnShare.hidden = YES;
    _btnRecord.hidden = YES;
    _btnPrivateChat.hidden = YES;
    
    giftview.alpha = 1;
    [self bringSubviewToFront:giftview];
    [UIView animateWithDuration:0.5 animations:^{
        giftview.frame = CGRectMake(0,SCREEN_HEIGHT/3*2, SCREEN_WIDTH, SCREEN_HEIGHT/3);
    }];
}

- (void)clickPrivateChat:(UIButton *)button {
    NSLog(@"点击私信");
    
    [_btnPrivateChat setImage:[UIImage imageNamed:@"live_per_info"] forState:UIControlStateNormal];
    
    
    //[self addSubview:_msgView];
    _msgView.hidden = NO;
    [self bringSubviewToFront:_msgView];
}
- (void)chatListConversations {
}

-(void)clickShare:(UIButton *)button{
    if (self.delegate) [self.delegate clickShare:button];
}

-(void)clickRecord:(UIButton *)button{
    if (self.delegate) {
        [self.delegate clickRecord:button];
    }
}

-(void)showLikeHeart{
    [self showLikeHeartStartRect:_praiseBtn.frame];
}

- (void)showLikeHeartStartRect:(CGRect)frame
{
    {
        // 星星动画频率限制
        static TCFrequeControl *freqControl = nil;
        if (freqControl == nil) {
            freqControl = [[TCFrequeControl alloc] initWithCounts:10 andSeconds:1];
        }
        
        if (![freqControl canTrigger]) {
            return;
        }
    }
    
    if (_viewsHidden) {
        return;
    }
    UIImageView *imageView = [[UIImageView alloc ] initWithFrame:frame];
    imageView.image = [[UIImage imageNamed:@"img_like"] imageWithTintColor:[UIColor randomFlatDarkColor]];
    [self addSubview:imageView];
    imageView.alpha = 0;
    
    
    [imageView.layer addAnimation:[self hearAnimationFrom:frame] forKey:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [imageView removeFromSuperview];
    });
}

- (CAAnimation *)hearAnimationFrom:(CGRect)frame
{
    //位置
    CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.beginTime = 0.5;
    animation.duration = 2.5;
    animation.removedOnCompletion = YES;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount= 0;
    animation.calculationMode = kCAAnimationCubicPaced;
    
    CGMutablePathRef curvedPath = CGPathCreateMutable();
    CGPoint point0 = CGPointMake(frame.origin.x + frame.size.width / 2, frame.origin.y + frame.size.height / 2);
    
    CGPathMoveToPoint(curvedPath, NULL, point0.x, point0.y);
    
    if (!_heartAnimationPoints) {
        _heartAnimationPoints = [[NSMutableArray alloc] init];
    }
    if ([_heartAnimationPoints count] < 40) {
        float x11 = point0.x - arc4random() % 30 + 30;
        float y11 = frame.origin.y - arc4random() % 60 ;
        float x1 = point0.x - arc4random() % 15 + 15;
        float y1 = frame.origin.y - arc4random() % 60 - 30;
        CGPoint point1 = CGPointMake(x11, y11);
        CGPoint point2 = CGPointMake(x1, y1);
        
        int conffset2 = self.superview.bounds.size.width * 0.2;
        int conffset21 = self.superview.bounds.size.width * 0.1;
        float x2 = point0.x - arc4random() % conffset2 + conffset2;
        float y2 = arc4random() % 30 + 240;
        float x21 = point0.x - arc4random() % conffset21  + conffset21;
        float y21 = (y2 + y1) / 2 + arc4random() % 30 - 30;
        CGPoint point3 = CGPointMake(x21, y21);
        CGPoint point4 = CGPointMake(x2, y2);
        
        [_heartAnimationPoints addObject:[NSValue valueWithCGPoint:point1]];
        [_heartAnimationPoints addObject:[NSValue valueWithCGPoint:point2]];
        [_heartAnimationPoints addObject:[NSValue valueWithCGPoint:point3]];
        [_heartAnimationPoints addObject:[NSValue valueWithCGPoint:point4]];
    }
    
    // 从_heartAnimationPoints中随机选取一组point
    int idx = arc4random() % ([_heartAnimationPoints count]/4);
    CGPoint p1 = [[_heartAnimationPoints objectAtIndex:4*idx] CGPointValue];
    CGPoint p2 = [[_heartAnimationPoints objectAtIndex:4*idx+1] CGPointValue];
    CGPoint p3 = [[_heartAnimationPoints objectAtIndex:4*idx+2] CGPointValue];
    CGPoint p4 = [[_heartAnimationPoints objectAtIndex:4*idx+3] CGPointValue];
    CGPathAddQuadCurveToPoint(curvedPath, NULL, p1.x, p1.y, p2.x, p2.y);
    CGPathAddQuadCurveToPoint(curvedPath, NULL, p3.x, p3.y, p4.x, p4.y);
    
    
    animation.path = curvedPath;
    
    CGPathRelease(curvedPath);
    
    //透明度变化
    CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnim.fromValue = [NSNumber numberWithFloat:1.0];
    opacityAnim.toValue = [NSNumber numberWithFloat:0];
    opacityAnim.removedOnCompletion = NO;
    opacityAnim.beginTime = 0;
    opacityAnim.duration = 3;
    
    //比例
    CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    //        int scale = arc4random() % 5 + 5;
    scaleAnim.fromValue = [NSNumber numberWithFloat:.0];//[NSNumber numberWithFloat:((float)scale / 10)];
    scaleAnim.toValue = [NSNumber numberWithFloat:1];
    scaleAnim.removedOnCompletion = NO;
    scaleAnim.fillMode = kCAFillModeForwards;
    scaleAnim.duration = .5;
    
    CAAnimationGroup *animGroup = [CAAnimationGroup animation];
    animGroup.animations = [NSArray arrayWithObjects: scaleAnim,opacityAnim,animation, nil];
    animGroup.duration = 3;
    
    return animGroup;
}

//监听键盘高度变化
-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;
    [UIView animateWithDuration:0.25 animations:^{
        if (endFrame.origin.y == self.height) {
            _msgInputView.y =  endFrame.origin.y;
        }else{
            if (_vChat.isHidden == YES) {
                _msgInputView.y =  endFrame.origin.y - _msgInputView.height;
            }
        }
    }];
}

// 监听登出消息
- (void)onLogout:(NSNotification*)notice {
    [self closeVC];
}

#pragma mark TCPlayDecorateDelegate
-(void)closeVC{
    if (self.delegate && [self.delegate respondsToSelector:@selector(closeVC:)]) {
        [_bulletViewOne stopAnimation];
        [_bulletViewTwo stopAnimation];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        
        //直播更新在线人数和点赞数到列表页
        if (TCLiveListItemType_Live == _liveInfo.type)
        {
            int viewerCount = [_topView getViewerCount] > 0 ? (int)[_topView getViewerCount] - 1 : 0;
            [[TCLiveListMgr sharedMgr] update:_liveInfo.userid viewerCount:viewerCount likeCount:(int)[_topView getLikeCount]];
        }
        
        [self.delegate closeVC: YES];
    }
}
-(void)clickScreen:(UITapGestureRecognizer *)gestureRecognizer{
    [_msgInputFeild resignFirstResponder];
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickScreen:)]) {
        [self.delegate clickScreen:gestureRecognizer];
    }
}

//调用声网的（目前其实不是doubleclick是单次）
- (void)doDoubleTapped:(UITapGestureRecognizer *)sender
{
    [self.delegate doDoubleTapped:sender];
}

-(void)clickPlayVod{
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickPlayVod)]) {
        [self.delegate clickPlayVod];
    }
}

-(void)onSeek:(UISlider *)slider{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onSeek:)]) {
        [self.delegate onSeek:slider];
    }
}

-(void)onSeekBegin:(UISlider *)slider{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onSeekBegin:)]) {
        [self.delegate onSeekBegin:slider];
    }
}

-(void)onDrag:(UISlider *)slider {
    if (self.delegate && [self.delegate respondsToSelector:@selector(onDrag:)]) {
        [self.delegate onDrag:slider];
    }
}

- (void)alertClick:(UIButton *)sender {
    NSLog(@"点击弹出 %d", sender.isSelected);
    _qingBgView.hidden = sender.isSelected;
    sender.selected = !sender.isSelected;
}

- (void)clickGao:(UIButton *)sender {
    _qingBgView.hidden = YES;
    _btnAlert.selected = !_btnAlert.isSelected;
    [_btnAlert setImage:[UIImage imageNamed:@"live_gao"] forState:UIControlStateNormal];
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickGao:)]) {
        [self.delegate clickGao:sender];
    }
}

- (void)clickBiao:(UIButton *)sender {
    _qingBgView.hidden = YES;
    _btnAlert.selected = !_btnAlert.isSelected;
    [_btnAlert setImage:[UIImage imageNamed:@"live_biao"] forState:UIControlStateNormal];
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickBiao:)]) {
        [self.delegate clickBiao:sender];
    }
}

- (void)clickDownShare:(UIButton *)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickDownShare:)]) {
        [self.delegate clickDownShare:sender];
    }
}

#pragma mark - AVIMMsgListener

-(void)onRecvGroupSender:(IMUserAble *)info textMsg:(NSString *)msgText{
    
    switch (info.cmdType) {
        case AVIMCMD_Custom_Text: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.uid;
            msgModel.userName = [info imUserName];
            msgModel.userMsg  =  msgText;
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.level = [NSString stringWithFormat:@"%@", info.level];
            msgModel.msgType = TCMsgModelType_NormalMsg;
            [self bulletMsg:msgModel];
            break;
        }
            
        case AVIMCMD_Custom_EnterLive: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  @"加入直播";
            msgModel.userHeadImageUrl = info.imUserIconUrl;
//            msgModel.level = info.level;
            msgModel.msgType = TCMsgModelType_MemberEnterRoom;
            
            //收到新增观众消息，判断只有没在观众列表中，数量才需要增加1
            if (![self isAlreadyInAudienceList:msgModel])
            {
                [_topView onUserEnterLiveRoom];
            }
            [self bulletMsg:msgModel];
            
            break;
        }
            
        case AVIMCMD_Custom_ExitLive: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  @"退出直播";
            msgModel.userHeadImageUrl = info.imUserIconUrl;
//            msgModel.level = info.level;
            msgModel.msgType = TCMsgModelType_MemberQuitRoom;
            
            [_topView onUserExitLiveRoom];
            [self bulletMsg:msgModel];
            
            break;
        }
            
        case AVIMCMD_Custom_Like: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  @"点了个赞";
            msgModel.userHeadImageUrl = info.imUserIconUrl;
//            msgModel.level = info.level;
            msgModel.msgType = TCMsgModelType_Praise;
            
            [self bulletMsg:msgModel];
            [self showLikeHeart];
            [_topView onUserSendLikeMessage];
            break;
        }
            
        case AVIMCMD_Custom_Danmaku: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  msgText;
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.level = info.level;
            msgModel.msgType = TCMsgModelType_DanmaMsg;
            
            [self bulletMsg:msgModel];
            break;
        }
            
        case AVIMCMD_Custom_Gift: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.uid;
            msgModel.userName = [info imUserName];
            msgModel.userMsg  =  msgText;
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_Gift;
            
//            NSData *jsonData = [msgText dataUsingEncoding:NSUTF8StringEncoding];
//            NSError *err;
//            NSDictionary *xiubiD = [NSJSONSerialization JSONObjectWithData:jsonData
//                                                                options:NSJSONReadingMutableContainers
//                                                                  error:&err];
            
            _xiubi.text = [NSString stringWithFormat:@"秀币 %@个", [msgText valueForKey:@"stars_count"]];
            
//            CGSize coinSize = [LZCTools textSizeWithText:_xiubi.text font:kUHSystemFontWithSize(10)];
//            _xiubi.width = coinSize.width;
            
            NSDictionary *giftDict = @{@"msg":msgModel.userMsg, @"nickName":msgModel.userName, @"headPic":msgModel.userHeadImageUrl, @"userId":[GetUserDefaule(USERINFO) valueForKey:@"user_id"]};
            // 礼物发送消息通知
            NSNotification *notification =[NSNotification notificationWithName:@"showGift" object:nil userInfo:giftDict];
            //通过通知中心发送通知
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            
            break;
        }
            
        case AVIMCMD_Custom_Banned: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.uid;
            msgModel.userName = [info imUserName];
            msgModel.userMsg  =  msgText;
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_Banned;
            
            [self bannedAction:msgModel];
            
            break;
        }
            
        case AVIMCMD_Custom_RemoveAudience: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.uid;
            msgModel.userName = [info imUserName];
            msgModel.userMsg  =  msgText;
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_RemoveAudience;
            
            [self removeAudience:msgModel];
            
            break;
        }
        case AVIMCMD_Custom_SetAdministrator: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.uid;
            msgModel.userName = [info imUserName];
            msgModel.userMsg  =  msgText;
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_SetAdministrator;
            
            [self setAdministrator:msgModel];
            
            break;
        }
        case AVIMCMD_Custom_DeleteAdministrator: {
            TCMsgModel *msgModel = [[TCMsgModel alloc] init];
            msgModel.userId = info.uid;
            msgModel.userName = [info imUserName];
            msgModel.userMsg  =  msgText;
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_RemoveAudience;
            
            [self deleteAdministrator:msgModel];
            
            break;
        }

            
        default:
            break;
    }
}

- (void)onRecvGroupSystemMessage:(TIMGroupSystemElem *)msg {
    // 群被解散
    if (msg.type == TIM_GROUP_SYSTEM_DELETE_GROUP_TYPE) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(onRecvGroupDeleteMsg)]) {
            [self.delegate onRecvGroupDeleteMsg];
        }
    }
}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    _msgInputFeild.text = @"";
    _privateChatTextF.text = @"";
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    _msgInputFeild.text = textField.text;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if ([textField isEqual:_msgInputFeild]) {
        
        NSString *textMsg = [textField.text stringByTrimmingCharactersInSet:[NSMutableCharacterSet whitespaceCharacterSet]];
        if (textMsg.length <= 0) {
            textField.text = @"";
            [HUDHelper alert:@"消息不能为空"];
            return YES;
        }
        
        NSDictionary *userInfo = GetUserDefaule(USERINFO);
        TCMsgModel *msgModel = [[TCMsgModel alloc] init];
        msgModel.userName = @"我";
        msgModel.userMsg  = textMsg;
        msgModel.userHeadImageUrl = userInfo[@"face"];
        msgModel.level = [NSString stringWithFormat:@"%@", userInfo[@"level"]];
        msgModel.userId = userInfo[@"user_id"];
        
        
        if (_bulletBtnIsOn) {
            msgModel.msgType  = TCMsgModelType_DanmaMsg;
            [_msgHandler sendDanmakuSenderInfo:_liveInfo.senderInfo msg:textMsg];
        }else{
            msgModel.msgType = TCMsgModelType_NormalMsg;
            [_msgHandler sendTextSenderInfo:_liveInfo.senderInfo msg:textMsg];
        }
        
        [self bulletMsg:msgModel];
        [_msgInputFeild resignFirstResponder];
    }
    else {
        
        [_msgHandler sendC2CSenderInfo:_liveInfo.senderInfo toSenderInfo:_receiveInfo msg:textField.text];
        [_privateChatTextF resignFirstResponder];
        _privateChatTextF.text = @"";
        [self getConversation:_currConversation];
        
    }
    
    
    return YES;
}


#pragma mark - 滑动隐藏界面UI

- (void)maskClick {
    _vChat.hidden = YES;
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    _touchBeginLocation = [touch locationInView:self];
        
    [UIView animateWithDuration:0.5 animations:^{
        giftview.frame = CGRectMake(0,SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT/3);
    }];
    
    _closeBtn.hidden = NO;
    _btnChat.hidden = NO;
//    _praiseBtn.hidden = NO;
//    _btnLog.hidden = NO;
    _btnGift.hidden = NO;
//    _btnShare.hidden = NO;
//    _btnRecord.hidden = NO;
    _btnPrivateChat.hidden = NO;
    
    
    _vChat.hidden = YES;
    _chatHead.text= @"私信";
    [_privateChatTextF resignFirstResponder];
    
    
    NSLog(@"你触发了decorateView这里的触摸事件 %@", _liveInfo.isPraise);
    
    if ([_liveInfo.isPraise isEqualToString:@"0"]) {
        
        NSString *url = [NSString stringWithFormat:@"%@/%@/likes", APILives, _liveInfo.roomid];
        
        [[NetworkTool sharedTool] requestWithName:@"直播间点赞" URLString:url parameters:nil method:@"POST" callBack:^(id responseObject) {
            
            _liveInfo.isPraise = @"1";
            // 一次点赞
            if ([_msgHandler sendLikeSenderInfo:_liveInfo.senderInfo]) {
                [[TCPlayerModel sharedInstance] giveLike:_liveInfo.userid handler:^(int errCode) {
                }];
                [_topView onUserSendLikeMessage];
            }
            [self showLikeHeartStartRect:_praiseBtn.frame];
            
        }];
    }
    
    
}


-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:self];
    [self endMove:location.x - _touchBeginLocation.x];
}


-(void)endMove:(CGFloat)moveX{
    
    
    [UIView animateWithDuration:0.2 animations:^{
        if(moveX > 10){
            for (UIView *view in self.subviews) {
                if (![view isEqual:_closeBtn]) {
                    CGRect rect = view.frame;
                    if (rect.origin.x >= 0 && rect.origin.x < SCREEN_WIDTH) {
                        rect = CGRectOffset(rect, self.width, 0);
                        view.frame = rect;
                        [self resetViewAlpha:view];
                    }
                }
            }
        }else if(moveX < -10){
            for (UIView *view in self.subviews) {
                if (![view isEqual:_closeBtn]) {
                    CGRect rect = view.frame;
                    if (rect.origin.x >= SCREEN_WIDTH) {
                        rect = CGRectOffset(rect, -self.width, 0);
                        view.frame = rect;
                        [self resetViewAlpha:view];
                    }
                    
                }
            }
        }
    }];
}

-(void)resetViewAlpha:(UIView *)view{
    CGRect rect = view.frame;
    if (rect.origin.x  >= SCREEN_WIDTH || rect.origin.x < 0) {
        view.alpha = 0;
        _viewsHidden = YES;
    }else{
        view.alpha = 1;
        _viewsHidden = NO;
    }
    if (view == _cover)
        _cover.alpha = 0.5;
}

#pragma mark AudienceListDelegate

-(void)onFetchGroupMemberList:(int)errCode memberCount:(int)memberCount
{
    /*	现在后台的批量查询用户接口返回的已经是包含目前所有直播间用户的数组，这里不必再次拉取,直接set人数
    [[TIMGroupManager sharedInstance] GetGroupMembers:_liveInfo.groupid succ:^(NSArray *members) {
        
        NSMutableArray *userArr = [[NSMutableArray alloc] init];
        for (TIMGroupMemberInfo *user in members) {
            [userArr addObject:user.member];
            [userArr removeObject:_liveInfo.myuserid];
        }
        NSLog(@"直播有多少成员%ld", userArr.count);
        
        if (_topView && 0 == errCode)
        {
            [_topView setViewerCount:(int)userArr.count likeCount:(int)[_topView getLikeCount]];
        }
        
    } fail:^(int code, NSString *msg) {
        NSLog(@"拉取当前成员失败 %d %@", code, msg);
    }];
    */
	if (_topView && 0 == errCode)
	{
		[_topView setViewerCount:memberCount likeCount:(int)[_topView getLikeCount]];
	}
}

#pragma mark =====私聊列表=====

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_tableView isEqual:tableView]) {
        
        MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chatList"];
        NSArray *arr = self.chatListArr[indexPath.row];
        NSDictionary *dict = arr[1];
        cell.nickName.text = dict[@"nickname"];
        [cell.headPic sd_setImageWithURL:[NSURL URLWithString:dict[@"headpic"]] placeholderImage:IMAGE(@"placeHolder")];
        cell.sign.text = arr[0];
        cell.date.hidden = YES;
        
        cell.contentView.tag = indexPath.row;
        [cell.contentView addTarget:self action:@selector(tableViewCellClick:)];
        
        return cell;
//
//        MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
//        cell.num.hidden = YES;
//        NSArray *arr = self.chatListArr[indexPath.row];
//        NSDictionary *dict = arr[1];
//        cell.nickName.text = dict[@"nickname"];
//        [cell.headPic sd_setImageWithURL:[NSURL URLWithString:dict[@"face"]] placeholderImage:IMAGE(@"placeHolder")];
//        
//        cell.accessoryType = UITableViewCellAccessoryNone;
//        cell.sign.hidden = NO;
//        CGSize nickNameSize = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)];
//        cell.nickName.frame = CGRectMake(20+SW(9), cell.headPic.centerY-nickNameSize.height-2, SW(2), nickNameSize.height);
//        cell.sign.text = arr[0];
//        if (![arr[2] isEqualToString:@"0"]) {
//            cell.num.text = arr[2];
//            cell.num.hidden = NO;
//        }
//        else
//            cell.num.hidden = YES;
//        cell.date.hidden = YES;
        
        // 点击过就隐藏
//        for (int i = 0; i < self.indexArr.count; i++) {
//            if ([self.indexArr[i] isEqualToString:[NSString stringWithFormat:@"%ld", indexPath.row]]) {
//                cell.num.hidden = YES;
//            }
//        }
        
//        return cell;
        
    }
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell2"];
        }
        
//        cell.textLabel.text = self.chatContentArr[indexPath.row];
//        cell.textLabel.text = @"222";
//        cell.imageView.image = IMAGE(@"placeHolder");
//        NSArray *arr = self.chatContentArr[indexPath.row];
//        NSDictionary *dict = arr[1];
//        cell.textLabel.text = arr[0];
//        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:dict[@"headpic"]] placeholderImage:IMAGE(@"placeHolder")];
        
        else{
            for (UIView *cellView in cell.subviews){
                [cellView removeFromSuperview];
            }
        }
        
        
        NSArray *arr = self.chatContentArr[indexPath.row];
        NSDictionary *dict = arr[1];
        
        //创建头像
        UIImageView *photo ;
        // 当前用户的
        if ([dict[@"uid"] isEqualToString:[GetUserDefaule(USERINFO) valueForKey:@"user_id"]]) {
            photo = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-60, 10, 50, 50)];
            photo.layer.cornerRadius = 25;
            photo.layer.masksToBounds = YES;
            [cell addSubview:photo];
            [photo sd_setImageWithURL:[NSURL URLWithString:dict[@"headpic"]] placeholderImage:IMAGE(@"placeHolder")];
            
            // 解析内容            // 文本
            [cell addSubview:[self bubbleView:arr[0] from:YES withPosition:65]];
            
            
        }else{
            photo = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 50, 50)];
            photo.layer.cornerRadius = 25;
            photo.layer.masksToBounds = YES;
            [cell addSubview:photo];
            [photo sd_setImageWithURL:[NSURL URLWithString:[[dict valueForKey:@"user_info"] valueForKey:@"face"]] placeholderImage:[UIImage imageNamed:@"placeHlder.png"]];
            
            [photo sd_setImageWithURL:[NSURL URLWithString:dict[@"headpic"]] placeholderImage:IMAGE(@"placeHolder")];
            
            // 解析内容
            [cell addSubview:[self bubbleView:arr[0] from:NO withPosition:65]];
            
        }
        
        return cell;
    }

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:_tableView]) {
        return self.chatListArr.count;
    }
    else
        return self.chatContentArr.count;
//    return 15;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 50;
    if ([tableView isEqual:_tableView]) {
        return SW(9)+20;
    }
    
    else if ([tableView isEqual:_tableView2]) {
        
        NSArray *arr = self.chatContentArr[indexPath.row];
        //        NSDictionary *dict = arr[1];
        //        NSDictionary *dict = [_dataArr objectAtIndex:indexPath.row];
        UIFont *font = [UIFont systemFontOfSize:14];
        CGSize size;
        size = [arr[0] sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
        
        return size.height+44;
        
        
    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    
}

- (void)tableViewCellClick:(UITableViewCell *)sender {
    
    _tableView2.hidden = NO;
    _textBgView.hidden = NO;
    
    UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer
                                             *)sender;
    
    NSInteger tag = [tapRecognizer.view tag];
    
    NSArray *arr = self.chatListArr[tag];
    NSDictionary *dict = arr[1];
    _chatHead.text = dict[@"nickname"];
    
    
    TIMConversation *conversation = self.conversationArr[tag];
    _currConversation = conversation;
    
    [self getConversation:conversation];
    
    
//
//    [[TIMManager sharedInstance] deleteConversation:TIM_C2C receiver:[NSString stringWithFormat:@"%@", conversation]];
    
}


//泡泡文本
- (UIView *)bubbleView:(NSString *)text from:(BOOL)fromSelf withPosition:(int)position{
    
    //计算大小
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    //    NSLog(@"%f,%f",size.width,size.height);
    
    
    //添加文本信息
    UILabel *bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?15.0f:22.0f, 20.0f, size.width+10, size.height+10)];
    bubbleText.backgroundColor = [UIColor clearColor];
    bubbleText.font = font;
    bubbleText.numberOfLines = 0;
    bubbleText.lineBreakMode = NSLineBreakByWordWrapping;
    //    bubbleText.text = text;
    //    bubbleText.text = [EaseConvertToCommonEmoticonsHelper convertToSystemEmoticons:text];
    bubbleText.text = text;
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCREEN_WIDTH-position-(bubbleText.frame.size.width+30.0f), 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 0.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    
    return returnView;
}


- (void)getConversation:(TIMConversation *)conversation {
    
    [self.chatContentArr removeAllObjects];
    
    [conversation getMessage:10 last:nil succ:^(NSArray *msgs) {
        for (TIMMessage *msg in msgs) {
            NSMutableArray *listArr = [[NSMutableArray alloc] init];
            for(int index = 0; index < [msg elemCount]; index++) {
                TIMElem *elem = [msg getElem:index];
                if([elem isKindOfClass:[TIMTextElem class]]) {
                    // 消息总入口频率限制
                    static TCFrequeControl *freqControl = nil;
                    if (freqControl == nil) {
                        freqControl = [[TCFrequeControl alloc] initWithCounts:20 andSeconds:1];
                    }
                    if (![freqControl canTrigger]) {
                        return;
                    }
                    // 文本消息
                    TIMTextElem *textElem = (TIMTextElem *)elem;
                    NSString *msgText = textElem.text;
                    NSDictionary* dict = [TCUtil jsonData2Dictionary:msgText];
                    NSLog(@"获取聊天信息 = %@", dict);
                    if (dict == nil) {
                        return;
                    }
                    NSError *err;
                    NSData *jsonData = [[dict valueForKey:@"senderInfo"] dataUsingEncoding:NSUTF8StringEncoding];
                    NSDictionary *infoDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                             options:NSJSONReadingMutableContainers
                                                                               error:&err];
                    //                    NSLog(@"---Json = %@", [dict valueForKey:@"senderInfo"]);
                    //                    [self.chatContentArr addObject:infoDict];
//                    _receiveInfo = dict[@"receiverInfo"];
                    
                    
                    NSString *currId = [GetUserDefaule(USERINFO) valueForKey:@"user_id"];
                    
//                    NSLog(@"当前用户id %@", currId);
                    
//                    NSLog(@"senderInfo = %@\nreceiverInfo = %@", dict[@"senderInfo"], dict[@"receiverInfo"]);
                    
                    if ([currId isEqualToString:infoDict[@"uid"]]) {
                        _receiveInfo = dict[@"receiverInfo"];
                    }
                    else {
                        _receiveInfo = dict[@"senderInfo"];
                    }
                        [listArr addObject:dict[@"msg"]];
                        [listArr addObject:infoDict];
                    
                    [self.chatContentArr addObject:listArr];
                    
//                    NSLog(@"消息数组1%@", self.chatContentArr);
                }
                else if([elem isKindOfClass:[TIMCustomElem class]]) {
                    // 自定义消息
                    TIMCustomElem* cele = (TIMCustomElem*)elem;
                    NSString *dataStr = [[NSString alloc] initWithData:cele.data encoding:NSUTF8StringEncoding];
                    DebugLog(@"datastr is:%@", dataStr);
                }
            }
        }
        // 数组倒序
        self.chatContentArr = (NSMutableArray *)[[self.chatContentArr reverseObjectEnumerator] allObjects];
        [_tableView2 reloadData];
        // 滑到底部
        if (_tableView2.contentSize.height > _tableView2.frame.size.height)
        {
            CGPoint offset = CGPointMake(0, _tableView2.contentSize.height - _tableView2.frame.size.height);
            [_tableView2 setContentOffset:offset animated:YES];
        }
        
    } fail:^(int code, NSString *msg) {
        NSLog(@"%d, %@", code, msg);
    }];

}

- (NSMutableArray *)conversationArr {
    if (_conversationArr == nil) {
        _conversationArr = [[NSMutableArray alloc] init];
    }
    return _conversationArr;
}
- (NSMutableArray *)chatListArr {
    if (_chatListArr == nil) {
        _chatListArr = [[NSMutableArray alloc] init];
    }
    return _chatListArr;
}
- (NSMutableArray *)chatContentArr {
    if (_chatContentArr == nil) {
        _chatContentArr = [[NSMutableArray alloc] init];
    }
    return _chatContentArr;
}

#pragma mark =====通知响应=====
- (void)sendGiftMsg:(NSNotification *)notification {
    
    NSDictionary *gift = notification.userInfo;
    NSLog(@"--接收到发送礼物的消息通知--\n%@", gift);
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:gift options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *giftStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    [_msgHandler sendGiftSenderInfo:_liveInfo.senderInfo msg:giftStr];
}
- (void)sendBannedMsg:(NSNotification *)notification {
    NSDictionary *banned = notification.userInfo;
    NSLog(@"--接收到禁言的消息通知--\n%@", banned);
    [_msgHandler sendBannedSenderInfo:_liveInfo.senderInfo msg:banned[@"id"]];
}
- (void)sendRemoveAudienceMsg:(NSNotification *)notification {
    NSDictionary *removeAudience = notification.userInfo;
    NSLog(@"--接收到踢人的消息通知--\n%@", removeAudience);
    [_msgHandler sendRemoveAudienceSenderInfo:_liveInfo.senderInfo msg:removeAudience[@"id"]];
}
- (void)SendFavoritesMsg:(NSNotification *)notification {
    NSDictionary *Favorites = notification.userInfo;
    NSLog(@"--接收观众关注主播通知--\n%@", Favorites);
    [_msgHandler sendFavoritesSenderInfo:_liveInfo.senderInfo msg:@""];
}
- (void)sendPrivateChatMsg:(NSNotification *)notification {
    NSDictionary *privateChat = notification.userInfo;
    
    _msgView.hidden = NO;
    [self bringSubviewToFront:_msgView];
    // 发送私聊消息通知
    NSNotification *not =[NSNotification notificationWithName:@"msgchatVC" object:nil userInfo:privateChat];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:not];
    
}
- (void)c2cNotification:(NSNotification *)notification {
    NSLog(@"--接收到私聊提醒通知--\n%@", notification.userInfo);
    if (_vChat.isHidden == YES) {
        [_btnPrivateChat setImage:IMAGE(@"live_per_infored") forState:UIControlStateNormal];
    }
    else if (_tableView2.isHidden == YES) {
        [self chatListConversations];
    }
    else
        [self getConversation:_currConversation];
    
}

#pragma mark ===== 66 - 69 响应=====
// 设置管理员
- (void)setAdministrator:(TCMsgModel *)model {
    // 如果当前用户属于被踢出的用户，执行退出直播间操作
    if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:model.userMsg]) {
		SetUserDefaule(@"1", SelfAdmin);
        [LZCTools HUDMessage:@"你被当前房主设置为TA的管理员" delay:1.0f];
    }
}
// 删除管理员
- (void)deleteAdministrator:(TCMsgModel *)model {
    // 如果当前用户属于被踢出的用户，执行退出直播间操作
    if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:model.userMsg]) {
		SetUserDefaule(@"0", SelfAdmin);
        [LZCTools HUDMessage:@"你从当前房主的管理员名单中移除" delay:1.0f];
    }
}
// 踢出观众
- (void)removeAudience:(TCMsgModel *)model {
    
    // 如果当前用户属于被踢出的用户，执行退出直播间操作
    if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:model.userMsg]) {
        [self closeVC];
        
        [LZCTools HUDMessage:@"你被踢出了房间" delay:1.0f];
        
    }
    
}
// 禁言
- (void)bannedAction:(TCMsgModel *)model {
    
    // 如果当前用户属于被禁言的用户
    if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:model.userMsg]) {
        
        [LZCTools HUDMessage:@"你被当前房主或者管理员禁言" delay:1.0f];
        
        _second = 10;
        if (_timer==nil) {
            _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
            // 开启定时器
            [_timer setFireDate:[NSDate distantPast]];
        }
    }
    
}
- (void)timerAction {
    
    NSLog(@"%d", _second);
    
    if (_second == 0) {
        
        [_timer invalidate];
        _timer = nil;
        
        [LZCTools HUDMessage:@"当前房间禁言时间结束" delay:1.0f];

        
    }
    else
        _second--;
}


@end
